package com.xzx.masterslave.masterslave.service.impl;

import com.xzx.masterslave.masterslave.annotation.ReadAnnonation;
import com.xzx.masterslave.masterslave.annotation.WriteAnnonation;
import com.xzx.masterslave.masterslave.entity.UserInfo;
import com.xzx.masterslave.masterslave.mapper.UserInfoMapper;
import com.xzx.masterslave.masterslave.service.UserInforService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class UserInfoServiceImpl implements UserInforService {
    @Resource
    private UserInfoMapper mapper;

    @WriteAnnonation("write")
    @Override
    public void add() {

        UserInfo userInfo = new UserInfo();
        userInfo.setName("小名1");
        userInfo.setAge(10);
        userInfo.setAddress("回家");
        mapper.insert(userInfo);
        log.info("执行数据库插入");
    }

    @ReadAnnonation("read")
    @Override
    public UserInfo queryById(Integer id) {
        UserInfo userInfo = mapper.queryById(id);
        return userInfo;
    }

    @WriteAnnonation("write")
    @Override
    public void updateUserInfo(UserInfo userInfo){
        Integer number = mapper.updateUserInfo(userInfo);
        log.info("number===>"+number);
    }


    @Override
    public UserInfo updateAndQuery(Integer id) {
        UserInfo userInfo = getProxyObject().queryById(id);
        userInfo.setAddress("我是一个好人");
        userInfo.setName("成龙");
        userInfo.setAge(70);
        getProxyObject().updateUserInfo(userInfo);
        return userInfo;
    }

    /**
     * AopContext强制获取代理对象
     * @return
     */
    private UserInfoServiceImpl getProxyObject(){
        return AopContext.currentProxy() != null ? (UserInfoServiceImpl)AopContext.currentProxy():this;
    }
}
